import { useState, useEffect } from 'react';
import { BrowserConfigComponentProps, BrowserProxyConfig, BrowserConfig } from './types';

export const BrowserConfigComponent = ({ config, onChange }: BrowserConfigComponentProps) => {
  const [localConfig, setLocalConfig] = useState(config);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [showProxyPassword, setShowProxyPassword] = useState(false);

  // 验证单个字段
  const validateField = (name: string, value: any, config: BrowserConfig): string => {
    switch (name) {
      case 'chrome_instance_path':
        if (value && !/\.(exe|chrome)$/i.test(value)) {
          return '必须指向有效的浏览器可执行文件';
        }
        return '';

      case 'proxy':
        if (config.proxy_enabled) {
          const proxy = value as BrowserProxyConfig;
          if (!proxy.server) return '代理服务器地址为必填项';
          if (!/^(https?|socks[45]):\/\/\S+:\d+$/.test(proxy.server)) {
            return '代理地址格式应为协议://主机:端口';
          }
          if (Boolean(proxy.username) !== Boolean(proxy.password)) {
            return '用户名和密码必须同时填写或留空';
          }
        }
        return '';

      default:
        return '';
    }
  };

  // 验证整个表单
  const validateForm = (config: BrowserConfig): Record<string, string> => {
    const errors: Record<string, string> = {};

    // 浏览器路径验证
    if (config.chrome_instance_path) {
      const pathError = validateField('chrome_instance_path', config.chrome_instance_path, config);
      if (pathError) errors.chrome_instance_path = pathError;
    }

    // 代理配置验证
    if (config.proxy_enabled) {
      const proxyError = validateField('proxy', config.proxy, config);
      if (proxyError) errors.proxy = proxyError;
    }

    return errors;
  };

  // 处理触摸状态（用户是否与字段交互过）
  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    const { name } = e.target;
    setTouched(prev => ({ ...prev, [name]: true }));
    
    // 特殊处理代理字段
    let error = '';
    if (['server', 'username', 'password'].includes(name)) {
      error = validateField('proxy', localConfig.proxy, localConfig);
    } else {
      error = validateField(name, localConfig[name as keyof BrowserConfig], localConfig);
    }
    
    setErrors(prev => ({ ...prev, [name]: error }));
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    let parsedValue: string | number | boolean = value;
    
    if (['headless', 'disable_security', 'proxy_enabled'].includes(name)) {
      parsedValue = (e.target as HTMLInputElement).checked;
    }

    let updatedConfig = { ...localConfig };
    
    // 处理代理字段
    if (['server', 'username', 'password'].includes(name)) {
      const currentProxy = updatedConfig.proxy || {
        server: '',
        username: '',
        password: ''
      };
      
      updatedConfig.proxy = {
        ...currentProxy,
        [name]: parsedValue as string
      } as BrowserProxyConfig;
    } else {
      // 对于非代理字段，直接更新根级别的配置
      updatedConfig = {
        ...updatedConfig,
        [name]: parsedValue
      };
    }
    
    setLocalConfig(updatedConfig);
    
    // 如果字段已经被触摸过，验证它
    if (touched[name]) {
      const error = validateField(name, parsedValue, updatedConfig);
      setErrors(prev => ({ ...prev, [name]: error }));
    }
    
    onChange(updatedConfig);
  };

  const handleBooleanChange = (name: 'headless' | 'disable_security' | 'proxy_enabled') => {
    const updatedConfig = {
      ...localConfig,
      [name]: !localConfig[name]
    };

    // 如果禁用代理，清空代理配置
    if (name === 'proxy_enabled' && !updatedConfig.proxy_enabled) {
      updatedConfig.proxy = {
        server: '',
        username: '',
        password: ''
      };
    }
    
    setLocalConfig(updatedConfig);
    onChange(updatedConfig);
  };

  // 切换代理密码显示
  const toggleProxyPasswordVisibility = () => {
    setShowProxyPassword(!showProxyPassword);
  };

  // 初始验证
  useEffect(() => {
    const formErrors = validateForm(localConfig);
    setErrors(formErrors);
  }, []);

  return (
    <div className="space-y-6">
      <h2 className="text-lg font-medium">浏览器配置</h2>
      <p className="text-sm text-gray-500">配置自动化任务中使用的浏览器的设置。</p>
      
      <div className="space-y-4">
        <h3 className="text-md font-medium">浏览器设置</h3>
        
        <div className="flex items-center justify-between mb-4">
          <div>
            <label htmlFor="headless" className="text-sm text-gray-700">
              无头模式
            </label>
            <p className="text-xs text-gray-500">运行时不显示 UI 界面。</p>
          </div>
          <div 
            className="relative inline-block w-12 h-6 ml-4 cursor-pointer"
            onClick={() => handleBooleanChange('headless')}
          >
            <input
              type="checkbox"
              id="headless"
              name="headless"
              checked={localConfig.headless}
              onChange={handleInputChange}
              className="opacity-0 w-0 h-0 absolute"
            />
            <span 
              className={`absolute top-0 left-0 right-0 bottom-0 rounded-full transition-colors duration-200 ease-in-out ${localConfig.headless ? 'bg-blue-600' : 'bg-gray-300'}`}
            ></span>
            <span 
              className={`absolute left-1 bottom-1 bg-white w-4 h-4 rounded-full transition-transform duration-200 ease-in-out ${localConfig.headless ? 'transform translate-x-6' : ''}`}
            ></span>
          </div>
        </div>

        <div className="flex items-center justify-between mb-4">
          <div>
            <label htmlFor="disable_security" className="text-sm text-gray-700">
              禁用浏览器安全功能
            </label>
            <p className="text-xs text-gray-500">禁用浏览器的安全限制（警告：可能存在安全风险）。</p>
          </div>
          <div 
            className="relative inline-block w-12 h-6 ml-4 cursor-pointer"
            onClick={() => handleBooleanChange('disable_security')}
          >
            <input
              type="checkbox"
              id="disable_security"
              name="disable_security"
              checked={localConfig.disable_security}
              onChange={handleInputChange}
              className="opacity-0 w-0 h-0 absolute"
            />
            <span 
              className={`absolute top-0 left-0 right-0 bottom-0 rounded-full transition-colors duration-200 ease-in-out ${localConfig.disable_security ? 'bg-blue-600' : 'bg-gray-300'}`}
            ></span>
            <span 
              className={`absolute left-1 bottom-1 bg-white w-4 h-4 rounded-full transition-transform duration-200 ease-in-out ${localConfig.disable_security ? 'transform translate-x-6' : ''}`}
            ></span>
          </div>
        </div>
        
        <div>
          <label htmlFor="chrome_instance_path" className="block text-sm font-medium text-gray-700 mb-1">
            浏览器实例路径
          </label>
          <input
            type="text"
            id="chrome_instance_path"
            name="chrome_instance_path"
            value={localConfig.chrome_instance_path}
            onChange={handleInputChange}
            onBlur={handleBlur}
            className={`w-full p-2 border ${errors.chrome_instance_path ? 'border-red-500' : 'border-gray-300'} rounded-md`}
            placeholder="C:\Program Files\Google\Chrome\Application\chrome.exe"
          />
          {errors.chrome_instance_path && touched.chrome_instance_path && (
            <p className="mt-1 text-xs text-red-500">{errors.chrome_instance_path}</p>
          )}
          <p className="mt-1 text-xs text-gray-500">指定自定义Chrome浏览器的路径（留空使用默认浏览器）。</p>
        </div>
        
        <div className="space-y-4 mt-6">
          <h3 className="text-md font-medium">代理设置</h3>
          
          <div className="flex items-center justify-between mb-4">
            <div>
              <label htmlFor="proxy_enabled" className="text-sm text-gray-700">
                启用代理
              </label>
              <p className="text-xs text-gray-500">使用HTTP代理连接网站。</p>
            </div>
            <div 
              className="relative inline-block w-12 h-6 ml-4 cursor-pointer"
              onClick={() => handleBooleanChange('proxy_enabled')}
            >
              <input
                type="checkbox"
                id="proxy_enabled"
                name="proxy_enabled"
                checked={localConfig.proxy_enabled}
                onChange={handleInputChange}
                className="opacity-0 w-0 h-0 absolute"
              />
              <span 
                className={`absolute top-0 left-0 right-0 bottom-0 rounded-full transition-colors duration-200 ease-in-out ${localConfig.proxy_enabled ? 'bg-blue-600' : 'bg-gray-300'}`}
              ></span>
              <span 
                className={`absolute left-1 bottom-1 bg-white w-4 h-4 rounded-full transition-transform duration-200 ease-in-out ${localConfig.proxy_enabled ? 'transform translate-x-6' : ''}`}
              ></span>
            </div>
          </div>
          
          {localConfig.proxy_enabled && (
            <div className="space-y-4 border-t pt-4">
              <div>
                <label htmlFor="server" className="block text-sm font-medium text-gray-700 mb-1">
                  代理服务器地址
                </label>
                <input
                  type="text"
                  id="server"
                  name="server"
                  value={localConfig.proxy?.server || ''}
                  onChange={handleInputChange}
                  onBlur={handleBlur}
                  className={`w-full p-2 border ${errors.server ? 'border-red-500' : 'border-gray-300'} rounded-md`}
                  placeholder="http://proxy.example.com:8080"
                />
                {errors.server && touched.server && (
                  <p className="mt-1 text-xs text-red-500">{errors.server}</p>
                )}
              </div>

              <div>
                <label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
                  代理用户名
                </label>
                <input
                  type="text"
                  id="username"
                  name="username"
                  value={localConfig.proxy?.username || ''}
                  onChange={handleInputChange}
                  onBlur={handleBlur}
                  className="w-full p-2 border border-gray-300 rounded-md"
                  placeholder="用户名（可选）"
                />
              </div>

              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
                  代理密码
                </label>
                <div className="relative">
                  <input
                    type={showProxyPassword ? 'text' : 'password'}
                    id="password"
                    name="password"
                    value={localConfig.proxy?.password || ''}
                    onChange={handleInputChange}
                    onBlur={handleBlur}
                    className="w-full p-2 border border-gray-300 rounded-md pr-10"
                    placeholder="密码（可选）"
                  />
                  <button
                    type="button"
                    onClick={toggleProxyPasswordVisibility}
                    className="absolute inset-y-0 right-0 px-3 flex items-center"
                  >
                    <span className="text-gray-500">
                      {showProxyPassword ? '隐藏' : '显示'}
                    </span>
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}; 

export default BrowserConfigComponent;